﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using System.Xml;

public partial class _35newpart_Linq_XLINQ_LINQ_to_XML_之针对XML文件的添加_查询_更新和删除 : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindPerson();

        }
    }

    /// <summary>
    /// 帮定数据
    /// </summary>
    private void BindPerson()
    {
        ///加载指定的XML文件
        XDocument MyXML =XDocument.Load(Server.MapPath(XMlfilePath));
        

        // 使用查询语法获取Person集合
        var products = from p in MyXML.Root.Elements("person")//得到原素 Elements
                       select new
                       {
                           Name = p.Attribute("name").Value,
                           岁数 = p.Attribute("age").Value,
                           钱 = p.Attribute("salary").Value,
                           pV = p.Value//得到值 相当于outXML
                       };
        gvPerson.DataSource = products;
        gvPerson.DataBind();
        

    }

    string xMlfilePath = "Linq_XmlDataSource.xml";

    /// <summary>
    /// XML文件路径
    /// </summary>
    public string XMlfilePath
    {
        get { return xMlfilePath; }
        set { xMlfilePath = value; }
    }


    /// <summary>
    /// 添加数据事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        ///加载指定的XML文件
        XDocument MyXML = XDocument.Load(Server.MapPath(XMlfilePath));
        // 创建需要新增的XElement对象
        XElement person = new XElement("person",
                                new XAttribute("name", txtName.Text),
                                new XAttribute("age", txtAge.Text),
                                new XAttribute("salary", txtSalary.Text)
                                )
                                { Value =Guid.NewGuid().ToString()};//创建一个新的对象

        MyXML.Root.Add(person);
        Response.Write("添加成功" + Server.HtmlEncode(MyXML.ToString()).Replace("\r\n", "<br/>"));
        MyXML.Save(Server.MapPath(xMlfilePath));
        BindPerson();

    }
    protected void gvPerson_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvPerson.EditIndex = -1;
        BindPerson();
    }
    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvPerson_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        ///加载指定的XML文件
        XDocument MyXML = XDocument.Load(Server.MapPath(XMlfilePath));
        string key = gvPerson.DataKeys[e.RowIndex].Value.ToString();

        var updaterow = from p in MyXML.Root.Elements("person")
                        where p.Value == gvPerson.DataKeys[e.RowIndex].Value.ToString()
                        select p;
        updaterow.Remove();//删除对象
        MyXML.Save(Server.MapPath(XMlfilePath));//更新对象
        BindPerson();

    }
    protected void gvPerson_RowEditing(object sender, GridViewEditEventArgs e)
    {

        gvPerson.EditIndex = e.NewEditIndex;
        BindPerson();

    }

    /// <summary>
    /// 更新文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvPerson_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {        ///加载指定的XML文件
        XDocument MyXML = XDocument.Load(Server.MapPath(XMlfilePath));
        string key = gvPerson.DataKeys[e.RowIndex].Value.ToString();

        var updaterow = from p in MyXML.Root.Elements("person")
                        where p.Value == gvPerson.DataKeys[e.RowIndex].Value.ToString()
                            select p
                            ;
        /////////////////////执行更新操作
        var ono = updaterow.First();

        ono.SetAttributeValue("name", ((TextBox)gvPerson.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
        ono.SetAttributeValue("age", ((TextBox)gvPerson.Rows[e.RowIndex].Cells[2].Controls[0]).Text);
        ono.SetAttributeValue("salary", ((TextBox)gvPerson.Rows[e.RowIndex].Cells[3].Controls[0]).Text);

        MyXML.Save(Server.MapPath(XMlfilePath));//更新对象
        //更新成功
        Response.Write("添加成功" + Server.HtmlEncode(MyXML.ToString()).Replace("\r\n", "<br/>"));
        gvPerson.EditIndex = -1;
        BindPerson();
       

    }
    protected void gvPerson_SelectedIndexChanged(object sender, EventArgs e)
    {
        ///加载指定的XML文件
        XDocument MyXML = XDocument.Load(Server.MapPath(XMlfilePath));
        #region 得到当前选定的数据
        //查询得到当前编辑的行
        var Member = from p in MyXML.Root.Elements("person")//得到当前选的记录
                     where p.Value == gvPerson.SelectedValue.ToString()
                     select new
                     {
                         Name = p.Attribute("name").Value,
                         岁数 = p.Attribute("age").Value,
                         钱 = p.Attribute("salary").Value,
                         pV = p.Value//得到值 相当于outXML
                     }
                     ;
        //和上面一样的方法
        var Member1 = MyXML.Root.Elements("person")
                      .Where(p => p.Value == gvPerson.SelectedValue.ToString())
                      .Select(p => new
                      {
                          Name = p.Attribute("name").Value,
                          岁数 = p.Attribute("age").Value,
                          钱 = p.Attribute("salary").Value,
                          pV = p.Value//得到值 相当于outXML
                      })
                      ;
        dvPerson.DataSource = Member1;
        
        dvPerson.DataBind();
        BindPerson();
        #endregion
    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void dvPerson_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {
       
    }
    /// <summary>
    /// 更新事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void dvPerson_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        ///得到各个字段的值
        string name =  ((TextBox)dvPerson.Rows[0].Cells[1].Controls[0]).Text;
        string age =  ((TextBox)dvPerson.Rows[1].Cells[1].Controls[0]).Text;
        string salary =  ((TextBox)dvPerson.Rows[2].Cells[1].Controls[0]).Text;//得到值
        string key =(dvPerson.Rows[3].Cells[1].Text);

        XDocument MyXML = XDocument.Load(Server.MapPath(XMlfilePath));
        var updaterow = from p in MyXML.Root.Elements("person")
                        where p.Value == key
                        select p
                    ;
        /////////////////////执行更新操作
        var ono = updaterow.First();

        ono.SetAttributeValue("name", name);
        ono.SetAttributeValue("age", age);
        ono.SetAttributeValue("salary", salary);

        MyXML.Save(Server.MapPath(XMlfilePath));
        BindPerson();

        dvPerson.DataSource = updaterow.Where(p => p.Value == "");
        dvPerson.DataBind();
        //dvPerson.ChangeMode(DetailsViewMode.ReadOnly);
    }
}
